package com.live.luowang.MusicServie;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaBrowserServiceCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.live.luowang.R;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MusicService extends MediaBrowserServiceCompat implements Playback.Callback{
    public static boolean LOOP=false;
    public static boolean SHUFFLE =false;
    private MusicProvider musicProvider;
    public MediaSessionCompat mediaSession;
    private Playback playback;
    private List<MediaMetadataCompat> musicList=new ArrayList<>();
    private SharedPreferences sp;
    private int position=0;

    @Override
    public void onCreate() {
        super.onCreate();
        playback=new Playback(this);
        playback.setCallback(this);
        sp=getSharedPreferences("playMode",MODE_PRIVATE);
        mediaSession=new MediaSessionCompat(this, "MusicService");
        setSessionToken(mediaSession.getSessionToken());
        mediaSession.setCallback(new MediaSessionCallback());
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        musicProvider=new MusicProvider();
        registerReceiver(receiver,new IntentFilter("musicBarAction"));
    }

    private BroadcastReceiver receiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getIntExtra("action",0)){
                case 0:
                    if (musicList != null && !musicList.isEmpty()) {
                        handlePlayRequest(musicList.get(position));
                    }
                    break;
                case 1:
                    playback.pause();
                    break;
            }
        }
    };
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LOOP=sp.getBoolean("loop",false);
        SHUFFLE =sp.getBoolean("shuffle",false);
        if(intent.getBooleanExtra("click",false)){
            if (!intent.getBooleanExtra("musicList",false)){
                switch (intent.getIntExtra("type",0)){
                    case 0:
                        musicProvider.updateMusic();
                        break;
                    case 1:
                        musicProvider.updateRecommMusic();
                        break;
                    case 2:
                        musicProvider.updatePostaudioMusic();
                        break;
                    case 3:
                        musicProvider.updateDPostaudioMusic();
                }
            }
            musicList=musicProvider.getOrderList();
            position=intent.getIntExtra("position",0);
            if (SHUFFLE){
                String mediaID=musicList.get(position).getDescription().getMediaId();
                Collections.shuffle(musicList);
                for(int i=0;i<musicList.size();i++){
                    if (musicList.get(i).getDescription().getMediaId().equals(mediaID)){
                        position=i;
                        break;
                    }
                }
            }
            if (intent.getBooleanExtra("musicList",false)){
                playback.play(musicList.get(position));
            }
        }else if (intent.getBooleanExtra("pause",false)){
            playback.pause();
        }
        return START_STICKY;
    }

    private void handlePlayRequest(MediaMetadataCompat metadata) {
        playback.play(metadata);
    }

    private final class MediaSessionCallback extends MediaSessionCompat.Callback {
        @Override
        public void onPlay() {
            super.onPlay();
            if (musicList != null && !musicList.isEmpty()) {
                handlePlayRequest(musicList.get(position));
            }
        }

        @Override
        public void onPause() {
            super.onPause();
            playback.pause();
        }

        @Override
        public void onSkipToNext() {
            super.onSkipToNext();
            position++;
            if(musicList!=null && position>=musicList.size()){
                position=0;
            }
            handlePlayRequest(musicList.get(position));
        }

        @Override
        public void onSkipToPrevious() {
            super.onSkipToPrevious();
            position--;
            if(!musicList.isEmpty() && position<0){
                position=musicList.size()-1;
            }
            handlePlayRequest(musicList.get(position));
        }

        @Override
        public void onStop() {
            super.onStop();
            playback.stop();
            stopSelf();
        }

        @Override
        public void onSeekTo(long pos) {
            super.onSeekTo(pos);
            playback.seekTo((int) pos);
        }
    }

    @Nullable
    @Override
    public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid, @Nullable Bundle rootHints) {
        return new BrowserRoot("1",null);
    }

    @Override
    public void onLoadChildren(@NonNull String parentId, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {

    }

    @Override
    public void onCompletion() {
        if (LOOP){
            playback.seekTo(0);
        }else{
            if(musicList != null && !musicList.isEmpty()) {
                position++;
                if (musicList != null && position >= musicList.size()) {
                    position = 0;
                }
                handlePlayRequest(musicList.get(position));
            }
        }
    }

    @Override
    public void onPlaybackStatusChanged(int state) {
        long current = PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN;
        if (playback != null) {
            current = playback.getCurrentStreamPosition();
        }
        PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder();
        stateBuilder.setState(state, current, 1.0f);
        mediaSession.setPlaybackState(stateBuilder.build());
        sendNotification();
    }

    @Override
    public void onError(String  error) {
        Toast.makeText(MusicService.this, error, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void updateMetaDate(MediaMetadataCompat metadata) {
        mediaSession.setMetadata(metadata);
    }

    private void sendNotification(){
        //创建一个通知
        NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(this);
        //自定义通知界面
        final RemoteViews remoteView=new RemoteViews(getPackageName(),R.layout.notification_layout);
        //设置 属性参数
        if(playback.isPlaying()){//设置控制播放的按钮图片
            remoteView.setViewVisibility(R.id.NotificationPlay, View.GONE);
            remoteView.setViewVisibility(R.id.NotificationPause, View.VISIBLE);
        }else{
            remoteView.setViewVisibility(R.id.NotificationPause, View.GONE);
            remoteView.setViewVisibility(R.id.NotificationPlay, View.VISIBLE);
        }
        //歌名
        remoteView.setTextViewText(R.id.NotificationTitle, musicList.get(position).getString(MediaMetadataCompat.METADATA_KEY_TITLE));
        //歌手
        remoteView.setTextViewText(R.id.NotificationArtist, musicList.get(position).getString(MediaMetadataCompat.METADATA_KEY_ARTIST));
        //专辑图片
        String url=musicList.get(position).getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI);
        remoteView.setImageViewBitmap(R.id.NotificationImg,ImageLoader.getInstance().loadImageSync(url));
        //开始暂停点击
        Intent play=new Intent();
        play.setAction("musicBarAction");
        play.putExtra("action",0);
        PendingIntent intent_Play=PendingIntent.getBroadcast(this,0,play,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteView.setOnClickPendingIntent(R.id.NotificationPlay,intent_Play);
        Intent pause=new Intent();
        pause.setAction("musicBarAction");
        pause.putExtra("action",1);
        PendingIntent intent_Pause=PendingIntent.getBroadcast(this,1,pause,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteView.setOnClickPendingIntent(R.id.NotificationPause,intent_Pause);
        //通知栏点击
        Intent intent=new Intent(this,MusicPlayingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent=PendingIntent.getActivities(this,0, new Intent[]{intent},0);
        mBuilder.setContent(remoteView)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText(musicList.get(position).getString(MediaMetadataCompat.METADATA_KEY_ARTIST))//必须设置这三个属性，不然显示不出来
                .setContentTitle(musicList.get(position).getString(MediaMetadataCompat.METADATA_KEY_TITLE))
                .setContentIntent(pendingIntent);
        Notification notification=mBuilder.build();
        notification.bigContentView=remoteView;
        startForeground(1,notification);
    }
}
